#!/usr/bin/python3
# config
import getopt
import os
import sys
optStr = "n:r:t:j:c:"
INPUT_FILE = "./in.txt"
SAMPLE_FILE = "./cheat.cpp"
TARGET_FILE = "./tmp.out"
TARGET_FILE_FMT = "./bin/{}"
CPP_COMPILE = "g++ -std=c++14 -O2 -Wall -fsanitize=address -Wno-unused-result {} -o {}"


options = [
    "n",
    "r",
    "t",
    "j",
    "c"
]

config = dict()
# config["n"] = False
# config["r"] = False

googleStyleCheckFilter = "--filter=-whitespace,-build"

# ========================== =====


def createNewFile(path):
    
    folder = "/".join(path.split('/')[:-1])
    os.system("mkdir -p {}".format(folder))
    os.system("touch {}".format(path))
    os.system("cat {} > {}".format(SAMPLE_FILE, path))

def createMakeFile(path, filename):
    runFilePath = TARGET_FILE_FMT.format(filename) + '.out'
    content = '''{}: {}
	{}
clean:
	rm -rf ./bin
	mkdir -p ./bin
'''.format(runFilePath, path, CPP_COMPILE.format(path, runFilePath))
    f = open("./Makefile", "w")
    f.write(content)
    f.close()
    return runFilePath


def runFile(path):
    filename = ".".join(path.split('.')[:-1])
    os.system("mkdir -p {}".format(TARGET_FILE_FMT.format(os.path.split(path)[0])))
    TARGET_FILE = createMakeFile(path, filename)
    print("TARGET_FILE:", TARGET_FILE)
    ret = os.system("make")
    if ret != 0:
        print("Verdict: CE")
        exit()
    os.system("echo -------------")
    # os.system(CPP_RUN)
    CPP_RUN = "time {}".format(TARGET_FILE)
    run = CPP_RUN
    if not config.__contains__('r'):
        run = run + "< {}".format(INPUT_FILE)
    print("Log: running cpp cmd {}".format(run))
    os.system(run)

def checkCodingStyle(path):
    os.system("./google-cppstyle.py {} {}".format(googleStyleCheckFilter, path))

try:
    args, vals = getopt.getopt(sys.argv[1:], optStr, [])
except getopt.error as err:
    print(str(err))
    sys.exit(2)


opt_cnt = 0
for curArg, curVal in args:
    for opt in options:
        if curArg in ("-{}".format(opt)):
            config[opt] = curVal
            opt_cnt += 1

if (opt_cnt > 1):
    print("More than one options, I don't know what to do")
    exit()

print(config, vals)

if config.__contains__("j"):
    assert(vals.__len__() == 1)
    os.system("python3 ./j.py {} {}".format(config["j"], vals[0]))
elif config.__contains__("t"):
    assert(vals.__len__() == 0)
    checkCodingStyle(config["t"])
elif config.__contains__("n"):
    print("Log: creating new file")
    assert(vals.__len__() == 0)
    createNewFile(config["n"])
elif config.__contains__("c"):
    os.system("python3 ./j.py -s y {} {}".format(config["c"], vals[0]))
else:
    print("Log: running file")
    assert(vals.__len__() == 1)

    if not os.path.exists(vals[0]):
        print("Log: creating new file")
        createNewFile(vals[0])
    runFile(vals[0])

